package com.syp.auth.web.controller;

import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.syp.auth.domain.vo.AppVo;
import com.syp.auth.domain.vo.easyui.DataGrid;
import com.syp.auth.domain.vo.easyui.Json;
import com.syp.auth.export.annotation.SecurityNone;
import com.syp.auth.export.common.GeneralUserVo;
import com.syp.auth.export.common.GorgeousParameters;
import com.syp.auth.export.resource.AuthorizeResourceI;
import com.syp.auth.export.util.CurrentUserHolder;
import com.syp.auth.service.base.AppServiceI;

@Controller
@RequestMapping("/sys/app")
public class AppController {
	
	private static final Logger log = LoggerFactory.getLogger(AppController.class);
	
	@Autowired
	private AppServiceI appService = null;
	@Autowired
	private AuthorizeResourceI authorizeResource = null;

	/**
	 * 主页面
	 * 
	 * @return
	 */
	@RequestMapping("/main")
	public ModelAndView mainPage(@CookieValue(GorgeousParameters.AUTH_COOKIE_NAME) String sid) {
		ModelAndView mv = new ModelAndView("sys/app/app");
		GeneralUserVo guser = CurrentUserHolder.get();
		if (guser == null) {
			guser = this.authorizeResource.cuser(sid);
		}
		List<String> permitUrlList = guser.getPermitUrlList();
		mv.addObject("permitUrlList", permitUrlList);
		return mv;
	}

	/**
	 * 新增页面
	 * 
	 * @return
	 */
	@RequestMapping("/addPage")
	public String addPage() {
		return "sys/app/appAddEdit";
	}

	/**
	 * 编辑页面
	 * 
	 * @return
	 */
	@RequestMapping("/editPage")
	public String editPage() {
		return "sys/app/appAddEdit";
	}

	/**
	 * 查看页面
	 * 
	 * @return
	 */
	@RequestMapping("/showPage")
	public String showPage() {
		return "sys/app/appShow";
	}

	@RequestMapping("/add")
	@ResponseBody
	public Json add(AppVo app) {
		Json json = new Json();
		try {
			this.appService.add(app);
			json.setMsg("添加成功！");
			json.setSuccess(true);
		} catch (Exception e) {
			log.error("添加应用异常。", e);
			json.setMsg("添加失败，应用名已存在！");
		}

		return json;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Json delete(Long id) {
		Json json = new Json();
		try {
			boolean pass = this.appService.checkAppCanbeRemovedById(id);
			if (pass) {
				this.appService.delete(id);
				json.setSuccess(true);
				json.setMsg("删除成功！");
			} else {
				json.setSuccess(false);
				json.setMsg("应用不可以被删除，因为该应用下存在关联资源！");
			}
		} catch (Exception e) {
			log.error("删除应用异常。", e);
			json.setMsg("删除失败！");
		}

		return json;
	}

	@RequestMapping("/deleteBatch")
	@ResponseBody
	public Json deleteBatch(String idsString) {
		Json json = new Json();
		try {
			String[] arrId = idsString.split(",");
			List<Long> idList = new LinkedList<>();
			boolean success = true;
			String message = "";
			for (int i = 0; i < arrId.length; i++) {
				idList.add(Long.valueOf(arrId[i]));
				success = this.appService.checkAppCanbeRemovedById(idList.get(i));
				if (!success) {
					AppVo currentApp = this.appService.get(idList.get(i));
					message = "应用[" + currentApp.getAppName() + "]不可以被删除，因为该应用下存在关联资源！";
					break;
				}
			}
			if (success) {
				this.appService.deleteBatch(idList);
				json.setSuccess(true);
				json.setMsg("删除成功！");
			} else {
				json.setSuccess(false);
				json.setMsg(message);
			}
		} catch (Exception e) {
			log.error("批量删除异常。", e);
			json.setMsg("批量删除失败！");
		}

		return json;
	}

	@RequestMapping("/edit")
	@ResponseBody
	public Json edit(AppVo app) {
		Json json = new Json();
		try {
			app.setLastUpdate(Calendar.getInstance().getTime());
			this.appService.edit(app);
			json.setSuccess(true);
			json.setMsg("编辑成功！");
		} catch (Exception e) {
			log.error("编辑应用异常。", e);
			json.setMsg("编辑失败！");
		}

		return json;
	}

	@RequestMapping("/getObject")
	@ResponseBody
	public AppVo getObject(Long id) {
		return this.appService.get(id);
	}

	@RequestMapping("/list")
	@ResponseBody
	public List<AppVo> list(AppVo app) {
		List<AppVo> list = null;
		try {
			list = this.appService.list(app);
			if (list == null) {
				list = new LinkedList<>();
			}
		} catch (Exception e) {
			log.error("查询应用列表异常。", e);
			list = new LinkedList<>();
		}

		return list;
	}

	@RequestMapping("/dropdownListItems")
	@ResponseBody
	public List<AppVo> dropdownListItems(@RequestParam(name = "q", required = false) String param) {
		List<AppVo> list = null;
		try {
			list = this.appService.dropdownListItems(param);
			if (list == null) {
				list = new LinkedList<>();
			}
		} catch (Exception e) {
			log.error("查询应用列表异常。", e);
			list = new LinkedList<>();
		}

		return list;
	}

	@RequestMapping("/datagrid")
	@ResponseBody
	public DataGrid<AppVo> datagrid(AppVo app) {
		DataGrid<AppVo> datagrid = new DataGrid<>();
		try {
			Page<AppVo> page = this.appService.pagelist(app);
			datagrid.setTotal(page.getTotalElements());
			datagrid.setRows(page.getContent());
		} catch (Exception e) {
			log.error("查询应用列表异常。", e);
		}

		return datagrid;
	}

	@SecurityNone
	@RequestMapping("/checkAppCodeUnique")
	@ResponseBody
	public Json checkAppCodeUnique(String appCode) {
		Json json = new Json();
		try {
			boolean unique = this.appService.checkAppCodeUnique(appCode);

			json.setSuccess(unique);
			json.setMsg(unique ? "应用编码唯一!" : "应用编码已存在!");
		} catch (Exception e) {
			log.error("校验应用名唯一性", e);
		}

		return json;
	}

}
